/*
 * Copyright (C) 2017 Pingan, Inc. All Rights Reserved.
 */

package com.pingan.haofang.searchcloud.es.schema.type;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.common.xcontent.XContentBuilder;

import java.io.IOException;
import java.util.Objects;

/**
 * 类型工厂
 *
 * @author zhangbi617
 * @date 2017-07-13
 */
public class TypeFactory {

    private static final String TYPE_KEY = "type";
    private static final String INDEX_KEY = "index";
    private static final String STORE_KEY = "store";
    private static final String NULL_VALUE = "null_value";
    private static final String COPY_TO = "copy_to";
    private static final String ANALYZER = "analyzer";
    private static final String SEARCH_ANALYZER = "search_analyzer";
    private static final String IK_MAX_WORD = "ik_max_word";
    /**
     * 获取fieldType类型
     *
     * @param fieldMapping
     * @return
     */
    public static XContentBuilder getType(FieldMapping fieldMapping, XContentBuilder xContentBuilder) throws IOException {

        Objects.requireNonNull(fieldMapping);

        xContentBuilder.startObject();

        // COMMON
        xContentBuilder
                .field(TYPE_KEY, fieldMapping.getType())
                .field(INDEX_KEY, fieldMapping.isIndexed())
                .field(STORE_KEY, fieldMapping.isStored());
        if (CollectionUtils.isNotEmpty(fieldMapping.getCopyTo())) {
            xContentBuilder.field(COPY_TO, fieldMapping.getCopyTo());
        }
        if (StringUtils.isNotBlank(fieldMapping.getDefaultValue())) {
            xContentBuilder.field(NULL_VALUE, fieldMapping.getDefaultValue());
        }
        if (MetaFieldTypeMapper.TYPE_TEXT.equals(fieldMapping.getType())){
            xContentBuilder.field(ANALYZER, IK_MAX_WORD);
            xContentBuilder.field(SEARCH_ANALYZER, IK_MAX_WORD);
        }
        return xContentBuilder.endObject();

    }
}
